<?php
/**
 * Description of orgChart
 *
 * This class outputs the org chart to the screen.
 * The configuration object is passed by value to avoid accidental changes.
 *
 * Ivan Bliskavka
 */

include 'chartNode.php';
class orgChart {
    private $rootId, $depth, $title;
    private $dbRecords;
    private $rootNode, $nodeJS, $nodeIndexes;

    public function __construct($iRootId, $iDepth, $iTitle)
    {
        $this->rootId = $iRootId;
        $this->depth = $iDepth;
        $this->title = $iTitle;

        //Get employee data and populate $nodeItems, $nodeIndexes, $nodeCount
        $this->GetData();
        $this->buildTree();
    }
    private function GetData()
    {
        //Get $user, $password and $database
        include 'dbConn.php';

        //Query database for employee records
	$con = mysql_connect($server,$user,$password);
	if (!$con){die('Could not connect: ' . mysql_error());}
	@mysql_select_db($database) or die( "Unable to select database ".$database.".");

        $query="SELECT emp.`emp_number` AS id, rt.`erep_sup_emp_number` AS manager, CONCAT(emp.`emp_lastname`,', ',emp.`emp_firstname`) AS name, cst.`title` AS department, jt.jobtit_name as title
            FROM `hs_hr_employee` AS emp LEFT JOIN `hs_hr_emp_reportto` AS rt ON emp.`emp_number`=rt.`erep_sub_emp_number`
            LEFT JOIN `hs_hr_job_title` AS jt ON emp.`job_title_code`=jt.`jobtit_code`
            LEFT JOIN `hs_hr_compstructtree` AS cst ON emp.`work_station`=cst.`id`
            WHERE emp.`emp_status` != 'EST000'";

        $result = mysql_query($query) or die('3. Error querying employee info.');
        mysql_close();

	if(mysql_num_rows($result) > 0)
	{
            //Records were returned, build an associative array of chartNode from records. Employee ID is the key.
            while(list($id, $manager, $name, $department, $title) = mysql_fetch_array($result))
            {
                $this->dbRecords[$id] = new chartNode($id, $manager, $name, $department, $title);
            }
            return;
	}
        echo "ERROR: Query returned no data.";
    }
    private function buildTree()
    {
        //Finds the root node and calls it's function responsible for building the tree structure.
        $this->rootNode = $this->dbRecords[$this->rootId];
        if(!is_null($this->rootNode))
        {
            $this->rootNode->parent = -1;
            $this->rootNode->getChildNodes($this->dbRecords, $this->depth, $this->nodeIndexes);
            return;
        }
        echo "ERROR: Root node was not found.";
    }
    public function displayChart()
    {
        $this->rootNode->getJS($this->nodeJS);

        //load template
        //$myFile = 'lib/ECOTree/'.$GLOBALS['config']->templateFile;
        $myFile = $GLOBALS['config']->templateFile;
        $fh = fopen($myFile, 'r');
        $chart = fread($fh, filesize($myFile));
        fclose($fh);

        //Replace placeholders in template with newly generated data
        $chart = str_replace("<!--PLACEHOLDER:TITLE-->", $this->title, $chart);
        $chart = str_replace("/*PLACEHOLDER:NODES*/", $this->nodeJS, $chart);

        $JsIndexes ='';
        foreach ($this->nodeIndexes as $id){
            $JsIndexes .= "'$id',";
            if($this->nodeIndexes > 0)break;
        }
        $JsIndexes = substr($JsIndexes, 0, strlen($JsIndexes)-1);
        $chart = str_replace("/*PLACEHOLDER:INDEXES*/", $JsIndexes, $chart);

        if(count($this->nodeIndexes) > 200) $chart = str_replace("/*PLACEHODLER:COLLAPSE*/", "t.collapseAll();", $chart);

        //Output chart to browser
        echo $chart;
    }
    public function displayDisconnected()
    {
        //Some scenarios exist where a node or branch may be disconnected due to
        //a termination/deletion of a node above it. This function helps to
        //troubleshoot those situations.
        
        if (!empty($this->dbRecords) && !empty($this->nodeIndexes))
        {
            ?>
            <html>
                <body>
                    <p>The following is a list of employees that are not displayed in the chart. The disconnected records are highlighted</p>
                <table>
                    <tr>
                    <th>ID</th>
                    <th>Employee</th>
                    <th>Manager</th>
                    </tr>
            <?php
            foreach ($this->dbRecords as $id => $node)
            {
                if(!isset($this->nodeIndexes[$id]))
                {
                    ?>
                    <tr>
                        <td><?php echo $node->id; ?></td>
                        <td><?php echo $node->name; ?></td>
                        <td <?php if(!isset($this->dbRecords[$node->parent])) echo 'bgcolor=#ee5555'; ?> >
                        <?php echo $this->dbRecords[$node->parent]->name; ?></td>
                    </tr>
                    <?php
                }
            }
            ?>
                </table>
                </body>
                </html>
            <?php
        }

    }
}
?>
